package by.grsu.transport.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import by.grsu.transport.form.LoginForm;
import by.grsu.transport.service.LoginService;
import by.grsu.transport.service.ServiceManager;

public class LoginAction extends Action {

	private static final Logger logger = Logger.getLogger(LoginAction.class);

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String target = ForwardActionTo.FAIL;
		LoginForm loginForm = (LoginForm) form;
		ServiceManager serviceManager = ServiceManager.getDefault();
		LoginService loginService = serviceManager.getLoginService();

		if (loginForm != null) {
			if (ForwardActionTo.SUCCESS.equals(loginService.getLoginStatus(
					loginForm.getLogin(), loginForm.getPassword(), request).name())) {
				target = ForwardActionTo.SUCCESS;
				logger.info("Log in...");
			} else {
				ActionMessages errors = new ActionMessages();
				errors.add("invalidUserName", new ActionMessage(
						"error.login.fail", loginForm.getLogin()));
				saveErrors(request, errors);
				logger.error("Login or password are incorrect!");
			}
		}
		return mapping.findForward(target);
	}
}
